package com.sikaryofficial.information.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.information.domain.dto.req.IndustryNewsListReq;
import com.sikaryofficial.information.domain.dto.resp.IndustryNewsDTO;
import com.sikaryofficial.information.domain.entity.IndustryNews;
import com.sikaryofficial.information.domain.mapping.IndustryNewsMapping;
import com.sikaryofficial.information.service.IIndustryNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.sikaryofficial.common.core.constant.CacheBusinessConstants.INDUSTRYNEWS_PAGE_LIST_KEY;

/**
 * @author wuweihong
 * @create 2024/9/19 - 13:37
 * @description: 产业新闻同步管理
 **/

@Component
@Slf4j
public class IndustryNewsManager {
    @Autowired
    private IIndustryNewsService industryNewsService;

    @Autowired
    private RedisService redisService;

    public IndustryNewsDTO getInfo(Long industryNewsId) {
        IndustryNews industryNews = industryNewsService.getOne(new LambdaQueryWrapper<IndustryNews>()
                .eq(IndustryNews::getIndustryNewsId, industryNewsId)
                .eq(IndustryNews::getDeletedVersion, 0L)
        );
        if (Objects.isNull(industryNews)) {
            throw new ServiceException("the industryNews is not exist");
        }
        return IndustryNewsMapping.INSTANCE.coverToDTO(industryNews);
    }

    public IPage<IndustryNewsDTO> listPage(IndustryNewsListReq req) {
        // 分页查询产业新闻列表 根据发布时间排序
        Page<IndustryNewsDTO> customPage = new Page<>(req.getPageNum(), req.getPageSize());
        // 缓存数据
        String md5 = generateCacheKey(req);
        String cacheKey = MessageFormat.format(INDUSTRYNEWS_PAGE_LIST_KEY, md5);
        if (Boolean.TRUE.equals(redisService.hasKey(cacheKey))) {
            JSONObject cacheValue = redisService.getCacheObject(cacheKey);
            return Objects.nonNull(cacheValue) ? JSON.parseObject(cacheValue.toString(), new TypeReference<IPage<IndustryNewsDTO>>() {
            }) : null;
        }
        // 分页查询数据
        IPage<IndustryNewsDTO> industryNewsDTOIPage = industryNewsService.industryNewsList(customPage, req);
        if (CollUtil.isNotEmpty(industryNewsDTOIPage.getRecords())) {
            redisService.setCacheObject(cacheKey, industryNewsDTOIPage, 1L, TimeUnit.MINUTES);
        }else {
            redisService.setCacheObject(cacheKey, industryNewsDTOIPage, 10L, TimeUnit.SECONDS);
        }
        return industryNewsDTOIPage;
    }

    /**
     * 生成缓存key
     * 分页no + 分页size +
     *
     * @param req
     * @return
     */
    private String generateCacheKey(IndustryNewsListReq req) {
        String userIdStr = Objects.nonNull(SecurityUtils.getUserId()) ? SecurityUtils.getUserId().toString() : "";
        String extraInfoStr = "";
        return DigestUtil.md5Hex(req.getPageNum() + "_"
                + req.getPageSize() + "_"
                + userIdStr + "_"
                + extraInfoStr
        );
    }



}
